import Crypto from '@/components/libs/crypto.js';
    import '@/components/libs/hmac.js';
    import '@/components/libs/sha1.js';
    import {
        Base64
    } from '@/components/libs/base64.js';
    // import config from '@/config/index.js'
import api from "@/api/api";
    const uploadFileSize = 1024 * 1024 * 10; // 上传文件的大小限制10m
    const uploadFileSizeVideo = 1024 * 1024 * 100; // 上传文件的大小限制100m 视频
    // const accesskey = ''; // 自己去申请
    // const accessId = '' // 自己去申请
    export default {
        _getPolicy(expiration) {
            let policyText = {
                // "expiration": "2022-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                "expiration": expiration, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                "conditions": [
                    ["content-length-range", 0, uploadFileSize] // 设置上传文件的大小限制
                ]
            };

            return Base64.encode(JSON.stringify(policyText))
        },
        _getSignature(policy,accesskey) {
            let bytes = Crypto.HMAC(Crypto.SHA1, policy, accesskey, {
                asBytes: true
            });
            return Crypto.util.bytesToBase64(bytes);
        },
        computeSignature(accessKeySecret, canonicalString) {
          return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
        },
        _getSuffix(filename) {
            let pos = filename.lastIndexOf('.')
            let suffix = ''
            if (pos != -1) {
                suffix = filename.substring(pos)
            }
            return suffix;
        },
        getFileName(filename) {
            console.log('filename:', filename)
			let date = new Date();
			 let  nian = date.getFullYear();
			 let  yue = date.getMonth() + 1;
			 let  ri = date.getDate();
			 let dataTime=String(nian)+String(yue)+String(ri)
            return 'wx_img/'+dataTime+ '/' + new Date().getTime() + Math.random().toString(36).substring(3, 20) + this._getSuffix(filename)
        },
        getImage(imgLen) {
            return new Promise((resolve, reject) => {
                wx.chooseImage({
                    count: 9-imgLen, //默认9
                    sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'],
                    success: (res) => {
						if (res.tempFiles[0].size > uploadFileSize) {
						    wx.showToast({
						        title: '文件大小超过系统上传限制：10M',
						        icon: 'none',
						        duration: 1000
						    });
						    return;
						}
                        resolve(res)
                    }
                })
            });
        },
        getVideo() {
            return new Promise((resolve, reject) => {
                wx.chooseVideo({
                    count: 1,
                    sourceType: ['camera', 'album'],
                    success: function(res) {
                        if (res.size > uploadFileSizeVideo) {
                            wx.showToast({
                                title: '文件大小超过系统上传限制：' + uploadFileSize,
                                icon: 'none',
                                duration: 1000
                            });
                            return;
                        }
                        resolve(res.tempFilePath)
                    },
                    fail: () => {
                        wx.showToast({
                            title: '取消选择视频',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                })
            });
        },
        // 获取STS签名
        get_STS() {
            //读取接口
            return new Promise((resolve, reject) => {
                let name = new Date().getTime() + Math.random();
                let operate = 'uploadImg';
                let that = this;
                let url=api.apiMall+'app/common/aliyunsts/getToken'
                wx.request({
                    method: "GET",
                    url: url,
                    data: {
                      'type':'oss'
                        // name,
                        // operate,
                        // sign: Crypto.MD5(name + operate + "bayinabayin888").toString()
                    },
                    success(res) {
                      let accesskey=res.data.data.accessKeySecret
                      let expiration = res.data.data.expiration//有效时间
                      let policy = that._getPolicy(expiration);
                      let signature=that._getSignature(policy,accesskey)
                          let data = {
                              accessId: res.data.data.accessKeyId,
                              host: 'https://static.xpandago.net',  // 自己去申请
                              policy,
                              signature: signature,
                              stsToken: res.data.data.securityToken,
                          };
                          resolve(data)
                    },
                    error(err) {
                        reject(err)
                    }
                })
            })
            // 本地获取
            // return new Promise((resolve, reject) => {
            //     let policy = this._getPolicy();
            //     console.log('gg',policy)
            //     let res = {
            //         accessId: accessId,
            //         host: 'https://static.xpandago.net',  // 自己去申请
            //         policy,
            //         signature: this._getSignature(policy),
            //     };
            //     resolve(res)
            // })
        },
    };
